package com.showsu.editor.utils.remote;

import cn.hutool.http.HttpUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.showsu.editor.entity.platform.xhs.AwemeDetailPlatformResult;
import com.showsu.editor.entity.platform.xhs.XhsAwemeDetailResult;
import com.showsu.editor.enums.SuccessEnum;
import com.showsu.editor.service.IRemoteInterfaceRecordService;
import com.showsu.editor.service.IRemoteInterfaceWarnSmsRecordService;
import com.showsu.editor.utils.Constant;
import com.showsu.editor.utils.RetryUtils;
import com.showsu.editor.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;
import java.util.concurrent.Callable;

/**
 * @Author: William
 * @Description:
 * @Date: Created in 7:04 下午 2024/8/28
 * @Modified By:
 */
@Slf4j
@Component
public class R202Util {

    @Value("${r202API.url}")
    private String apiUrl;

    @Value("${r202API.token}")
    private String token;

    private static final int timeout = 15000;
    private static final int timeout25 = 25000;

    /**
     * 最多重试次数
     */
    private static final int RETRY_MAX_COUNT = 3;

    /**
     * 重试等待间隔
     */
    private static final int RETRY_WAIT_TIME = 1500;

    @Autowired
    private IRemoteInterfaceRecordService remoteInterfaceRecordService;

    @Autowired
    private IRemoteInterfaceWarnSmsRecordService remoteInterfaceWarnSmsRecordService;

    /**
     * 查询xhs笔记详情，这个接口是有实况图的
     * @param noteId
     * @return
     */
    public XhsAwemeDetailResult getXhsAwemeDetail1(String noteId, Long interfaceId) {
        if (StringUtils.isBlank(noteId)) {
            return null;
        }
        Type type = new TypeToken<AwemeDetailPlatformResult>(){}.getType();
        Gson gson = new Gson();
        XhsAwemeDetailResult result = new XhsAwemeDetailResult();
        String response = RetryUtils.retry(new Callable<String>() {
            @Override
            public String call() {
                try {
                    long start = System.currentTimeMillis();
                    StringBuilder url = new StringBuilder(apiUrl).append("/api/feed/v1/detail?token=").append(token).append("&noteId=").append(noteId);
                    String responseInner = HttpUtil.get(url.toString(), timeout);
                    log.info("R202Util查询xhs作品详情-live1-响应耗时:{}-noteId:{}", System.currentTimeMillis() - start, noteId);
                    AwemeDetailPlatformResult temp = gson.fromJson(responseInner, type);
                    if (temp != null
                            && (Constant.containsXhsAwemeNotExistHint(StringUtil.convertUnicodeToChinese(temp.getMsg()))
                                || Constant.containsXhsAwemeNotExistHint(StringUtil.convertUnicodeToChinese(temp.get_msg()))
                                || (!org.springframework.util.CollectionUtils.isEmpty(temp.getData())
                                        && temp.getData().get(0) != null
                                        && !org.springframework.util.CollectionUtils.isEmpty(temp.getData().get(0).getNote_list())
                                        && Constant.containsXhsAwemeNotExistHint(StringUtil.convertUnicodeToChinese(temp.getData().get(0).getNote_list().get(0).getText()))
                                    )
                                )
                    ) {
                        remoteInterfaceRecordService.add(interfaceId, SuccessEnum.SUCCESS.getCode());
                        return Constant.xhsAwemeNotExist0;
                    }
                    //如果平台那边报错再重试一次
                    if (temp == null || CollectionUtils.isEmpty(temp.getData())) {
                        remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                        return "";
                    }
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.SUCCESS.getCode());
                    return responseInner;
                } catch (Exception e) {
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                    log.error("R202Util.getXhsAwemeDetail1(String, Long) error, noteId:{}, e:{}", noteId, e);
                    return "";
                }
            }
        }, RETRY_MAX_COUNT, RETRY_WAIT_TIME);
        if (StringUtils.isBlank(response)) {
            remoteInterfaceWarnSmsRecordService.sendWarnSmsIn15mins(interfaceId,
                    new StringBuilder("noteId=").append(noteId).toString());
            return result;
        }
        if (response.equals(Constant.xhsAwemeNotExist0)) {
            return null;
        }
        try {
            AwemeDetailPlatformResult awemeDetailPlatformResult = gson.fromJson(response, type);
            result.setData(awemeDetailPlatformResult);
        } catch (Exception e) {
            log.error("R202Util.getXhsAwemeDetail1(String, Long) convert error, noteId:{}, e:{}", noteId, e);
        }
        return result;
    }

    /**
     * 查询xhs笔记详情，这个接口是有实况图的
     * @param noteId
     * @return
     */
    public XhsAwemeDetailResult getXhsAwemeDetail3(String noteId, Long interfaceId) {
        if (StringUtils.isBlank(noteId)) {
            return null;
        }
        Type type = new TypeToken<AwemeDetailPlatformResult>(){}.getType();
        Gson gson = new Gson();
        XhsAwemeDetailResult result = new XhsAwemeDetailResult();
        String response = RetryUtils.retry(new Callable<String>() {
            @Override
            public String call() {
                try {
                    long start = System.currentTimeMillis();
                    StringBuilder url = new StringBuilder(apiUrl).append("/api/feed/v3/detail?token=").append(token).append("&noteId=").append(noteId);
                    String responseInner = HttpUtil.get(url.toString(), timeout);
                    log.info("R202Util查询xhs作品详情-live3-响应耗时:{}-noteId:{}", System.currentTimeMillis() - start, noteId);
                    AwemeDetailPlatformResult temp = gson.fromJson(responseInner, type);
                    //如果平台那边报错再重试一次
                    if (temp == null || CollectionUtils.isEmpty(temp.getData())) {
                        remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                        return "";
                    }
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.SUCCESS.getCode());
                    return responseInner;
                } catch (Exception e) {
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                    log.error("R202Util.getXhsAwemeDetail3(String, Long) error, noteId:{}, e:{}", noteId, e);
                    return "";
                }
            }
        }, RETRY_MAX_COUNT, RETRY_WAIT_TIME);
        if (StringUtils.isBlank(response)) {
            remoteInterfaceWarnSmsRecordService.sendWarnSmsIn15mins(interfaceId,
                    new StringBuilder("noteId=").append(noteId).toString());
            return result;
        }
        try {
            AwemeDetailPlatformResult awemeDetailPlatformResult = gson.fromJson(response, type);
            result.setData(awemeDetailPlatformResult);
        } catch (Exception e) {
            log.error("R202Util.getXhsAwemeDetail3(String, Long) convert error, noteId:{}, e:{}", noteId, e);
        }
        return result;
    }

    public static void main(String[] args) {
        //String url = "http://154.39.106.199:8899/api/feed/v4/list?userId=61a750c8000000001000cc19&page=1&token=5dda27d6759e4094b4364f6a3f556e10";
        //String url = "http://154.39.106.199:8899/api/feed/search?keyword=刘德华&page=1&sort=0&token=5dda27d6759e4094b4364f6a3f556e10";
        //String url = "http://154.39.106.199:8899/api/feed/comment/list?noteId=66b340d7000000001e01f425&start=&token=5dda27d6759e4094b4364f6a3f556e10";
        String url = "http://154.39.106.199:8899/api/user/profile?userId=59eb384ee8ac2b306c18b583&token=5dda27d6759e4094b4364f6a3f556e10";
        String response = HttpUtil.get(url);
        System.out.println(response);
    }
}
